#!/bin/bash

# run_all_mpi_tests.sh
# 自动运行 tests/mpi_tests/ 下所有可执行文件，使用 mpiexec + LD_PRELOAD

if [ -n "$MPITRACER_LIB" ]; then
    TRACER_LIB="$MPITRACER_LIB/mpitracer.so"
    if [ -f "$TRACER_LIB" ]; then
        echo "✅ Using mpitracer from MPITRACER_LIB: $TRACER_LIB"
    else
        echo "⚠️  MPITRACER_LIB is set but $TRACER_LIB not found."
        TRACER_LIB=""
    fi
fi

if [ -z "$TRACER_LIB" ]; then
    # 尝试检查当前目录是否有 mpitracer.so
    if [ -f "./mpitracer.so" ]; then
        echo "✅ Using mpitracer.so from current directory"
        TRACER_LIB="mpitracer.so"
    else
        echo "⚠️  No MPITRACER_LIB set and ./mpitracer.so not found."
        echo "✅ Falling back to system/library-path mpitracer.so (if available)"
        TRACER_LIB="mpitracer.so"
    fi
fi

# 设置测试目录
TEST_DIR="./"

# 检查目录是否存在
if [ ! -d "$TEST_DIR" ]; then
    echo "Error: Directory $TEST_DIR does not exist."
    exit 1
fi

# 收集所有可执行文件到数组（排除脚本和非测试文件）
test_files=()
special_tests=()
for f in "$TEST_DIR"/*; do
    # 修复：用 -x 检查可执行性，同时排除 .sh 和 .py 脚本
    if [ -f "$f" ] && [ -x "$f" ] && [[ "$f" != *.sh ]] && [[ "$f" != *.py ]]; then
        test_name=$(basename "$f")
        case "$test_name" in
            "test_all_mpi_cpp")
                special_tests+=("$f:all")  # 格式: path:args
                ;;
            # 可以添加更多需要特殊参数的测试
            # "test_another")
            #     special_tests+=("$f:arg1:arg2")
            #     ;;
            *)
                test_files+=("$f")
                ;;
        esac
    fi
done

# 统计总数
total=$((${#test_files[@]} + ${#special_tests[@]}))
if [ $total -eq 0 ]; then
    echo "❌ No executable tests found in $TEST_DIR"
    exit 1
fi

echo "🏁 Found $total test(s) in $TEST_DIR"
echo "🧪 Running MPI tests with LD_PRELOAD=$TRACER_LIB"
echo "----------------------------------------"

# 初始化计数器
passed=0
failed=0
current=0

# 遍历所有可执行文件
for test_exec in "${test_files[@]}"; do
    current=$((current + 1))

    echo ""
    echo "($current/$total) 🚀 Running: $test_exec"
    echo "----------------------------------------"

    mpiexec -genv LD_PRELOAD="$TRACER_LIB" -n 4 "$test_exec"
    RET=$?

    if [ $RET -eq 0 ]; then
        echo "✅ PASSED: $test_exec"
        passed=$((passed + 1))
    else
        echo "❌ FAILED: $test_exec (exit code: $RET)"
        failed=$((failed + 1))
    fi
    echo "----------------------------------------"
done

for test_entry in "${special_tests[@]}"; do
    current=$((current + 1))

    # 解析测试路径和参数
    IFS=':' read -r test_exec test_args <<< "$test_entry"

    echo ""
    echo "($current/$total) 🚀 Running: $test_exec $test_args"
    echo "----------------------------------------"

    # 构造命令并运行
    if [ "$test_args" = "all" ]; then
        mpiexec -genv LD_PRELOAD="$TRACER_LIB" -n 4 "$test_exec" all
    else
        mpiexec -genv LD_PRELOAD="$TRACER_LIB" -n 4 "$test_exec"
    fi

    RET=$?

    if [ $RET -eq 0 ]; then
        echo "✅ PASSED: $test_exec"
        passed=$((passed + 1))
    else
        echo "❌ FAILED: $test_exec (exit code: $RET)"
        failed=$((failed + 1))
    fi
    if [ "$(basename "$test_exec")" = "test_all_mpi_cpp" ]; then
        echo "🔍 Checking MPI function coverage using check_mpi_coverage.py"
        # 优化：用通配符匹配所有日志文件，避免硬编码
        cat /dev/shm/mpi_trace_*.log > "./log.txt" 2>/dev/null  # 忽略不存在的文件错误
        python3 "./check_mpi_coverage.py" "./log.txt"
    fi
    echo "----------------------------------------"
done

echo ""
echo "✅ Passed: $passed"
echo "❌ Failed: $failed"
echo "📊 Total: $total tests run."

if [ $failed -eq 0 ]; then
    echo "🎉 All tests completed successfully."
    exit_code=0
else
    echo "💥 $failed test(s) failed."
    exit_code=1
fi

echo "🏁 Test suite finished."
exit $exit_code
